/**
 * 认证相关API
 * 对应后端AuthRouter.js中的路由
 */
import api from './axios';
import { STORAGE_KEYS, ROLE_TYPES } from '../constants/common';

/**
 * 用户登录响应数据接口
 */
export interface LoginResponse {
  token: string;         // JWT令牌
  user: {                // 用户基本信息
    id: string;          // 用户ID
    username: string;    // 用户名
    role: string;        // 角色名称
    roleId: number;      // 角色ID
    avatar?: string;     // 头像URL(可选)
  };
}

/**
 * 用户登录
 * 对应后端POST /adminapi/auth/login路由
 */
export const login = async (username: string, password: string, captcha?: string) => {
  try {
    const loginData: Record<string, string> = { 
      username, 
      password 
    };
    
    if (captcha) {
      loginData.captcha = captcha;
    }
    
    const response = await api.post('/auth/login', loginData);
    console.log('登录响应完整数据:', response.data);
    
    if (response.data && response.data.code === 200) {
      // 保存token（注意token位于响应根级别）
      if (response.data.token) {
        localStorage.setItem('token', response.data.token);
        localStorage.setItem(STORAGE_KEYS.TOKEN, response.data.token);
        console.log('Token已保存到localStorage');
      }
      
      // 保存用户信息
      if (response.data.data) {
        localStorage.setItem('userInfo', JSON.stringify(response.data.data));
        localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(response.data.data));
        console.log('用户信息已保存到localStorage');
        
        // 正确保存权限信息
        if (response.data.data.role && response.data.data.role.rights) {
          localStorage.setItem(STORAGE_KEYS.USER_RIGHTS, JSON.stringify(response.data.data.role.rights));
          console.log('权限列表已保存:', response.data.data.role.rights.length, '项');
        }
      }
      
      // 保存侧边栏菜单项（如果有）
      if (response.data.sidebarItems) {
        localStorage.setItem('sidebarItems', JSON.stringify(response.data.sidebarItems));
        console.log('侧边栏菜单已保存:', response.data.sidebarItems.length, '项');
        }
      
      // 返回整合后的数据以便组件使用
      return {
        ...response.data.data,
        token: response.data.token,
        sidebarItems: response.data.sidebarItems
      };
    } else {
      throw new Error(response.data.msg || '登录失败');
    }
  } catch (error) {
    console.error('登录失败:', error);
    throw error;
  }
};

/**
 * 获取角色默认权限
 * @param roleId 角色ID
 * @returns 默认权限列表
 */
function getDefaultRightsForRole(roleId: number) {
  // 基础权限，所有角色都拥有
  const baseRights = ['/home', '/user-profile'];
  
  // 根据角色添加权限
  if (roleId === 1 || roleId === ROLE_TYPES.SUPER_ADMIN) { // 超级管理员
    return [
      ...baseRights,
      '/user-manage', '/user-manage/list',
      '/right-manage', '/right-manage/role/list', '/right-manage/right/list',
      '/news-manage', '/news-manage/add', '/news-manage/draft', '/news-manage/category',
      '/audit-manage', '/audit-manage/audit', '/audit-manage/list',
      '/publish-manage', '/publish-manage/unpublished', '/publish-manage/published', '/publish-manage/sunset',
      '/system/settings'
    ];
  } else if (roleId === 2) { // 管理员
    return [
      ...baseRights,
      '/news-manage', '/news-manage/add', '/news-manage/draft', '/news-manage/category',
      '/audit-manage', '/audit-manage/audit', '/audit-manage/list',
      '/publish-manage', '/publish-manage/unpublished', '/publish-manage/published', '/publish-manage/sunset'
    ];
  } else { // 编辑
    return [
      ...baseRights,
      '/news-manage', '/news-manage/add', '/news-manage/draft'
    ];
  }
}

/**
 * 用户退出登录
 * 对应后端POST /adminapi/auth/logout路由
 */
export const logout = async () => {
  try {
    const response = await api.post('/auth/logout');
    
    // 清除本地存储的所有数据
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    localStorage.removeItem('sidebarItems');
    localStorage.removeItem(STORAGE_KEYS.TOKEN);
    localStorage.removeItem(STORAGE_KEYS.USER_INFO);
    localStorage.removeItem(STORAGE_KEYS.USER_RIGHTS);
    
    return response.data;
  } catch (error) {
    console.error('退出登录失败:', error);
    
    // 即使退出失败，也清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    localStorage.removeItem('sidebarItems');
    localStorage.removeItem(STORAGE_KEYS.TOKEN);
    localStorage.removeItem(STORAGE_KEYS.USER_INFO);
    localStorage.removeItem(STORAGE_KEYS.USER_RIGHTS);
    
    throw error;
  }
};

/**
 * 系统初始化（创建管理员）
 * 对应后端POST /adminapi/system/init路由
 */
export const initSystem = async (adminData: { username: string; password: string; email?: string; }) => {
  try {
    const response = await api.post('/system/init', adminData);
    return response.data;
  } catch (error) {
    console.error('系统初始化失败:', error);
    throw error;
  }
};

/**
 * 验证Token是否有效
 * 对应后端GET /adminapi/auth/validate-token路由
 */
export const verifyToken = async () => {
  try {
    const response = await api.get('/auth/validate-token');
    return response.data.code === 200;
  } catch {
    return false; // 请求失败表示token无效
  }
};

export default {
  login,
  logout,
  initSystem,
  verifyToken
};